package com.wys.spring;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class WYSHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public WYSHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        loadBody(request);
    }

    private byte[] body;

    private BufferedReader reader;

    private ServletInputStream inputStream;


    private void loadBody(HttpServletRequest request) throws IOException {
        body = IOUtils.toByteArray(request.getInputStream());
       // inputStream = new RequestCachingInputStream(body);
    }

    public byte[] getByteBody() {
        return body;
    }

    public String getStringBody() {
        return new String(body);
    }


    @Override
    public ServletInputStream getInputStream() {
        return new ServletInputStream() {
            final ByteArrayInputStream bais = new ByteArrayInputStream(body);
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return bais.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        reader = new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
        return reader;
    }

    private static class RequestCachingInputStream extends ServletInputStream {

        private final ByteArrayInputStream inputStream;

        public RequestCachingInputStream(byte[] bytes) {
            inputStream = new ByteArrayInputStream(bytes);
        }

        @Override
        public int read() throws IOException {
            return inputStream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readlistener) {
        }

    }
}
